# -*- encoding=utf8 -*-

__author__ = "code哥"
import random
import sys
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

dev = False

if dev:
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    from airtest.cli.parser import cli_setup

    if not cli_setup():
        auto_setup(__file__, logdir=None, devices=[
            "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
        ])
else:
    import timeout_decorator

    # M960BDPT226TA WIFI 10.0.0.26 48003
    argv1 = str(sys.argv[1])
    argv2 = str(sys.argv[2])
    argv3 = str(sys.argv[3])
    argv4 = str(sys.argv[4])

    if argv2 == 'USB':
        conn_info = 'Android://127.0.0.1:5037/{uuid}?cap_method=JAVACAP&&ori_method=ADBORI'.format(
            uuid=argv1)
        device = connect_device(conn_info)
    else:
        # WIFI模式
        conn_info = 'Android://127.0.0.1:5037/{clientIp}:{port}'.format(
            clientIp=argv3,
            port=argv4)
        print(conn_info)
        device = connect_device(conn_info)

    poco = AndroidUiautomationPoco(device, use_airtest_input=True, screenshot_each_action=False)

    logdir = "{path}/static/source_img/{fileName}/{devices}".format(
        path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        fileName=str(os.path.abspath(__file__).split('/')[-1]).split('.py')[0],
        devices=argv1)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    auto_setup(__file__,
               logdir=logdir,
               devices=[conn_info, ],
               project_root="{root}".format(root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def start():
    if not dev:
        set_logdir(logdir)
        set_current(str(sys.argv[1]))
    # 退到桌面
    home()
    stop_app('cn.youth.news')
    sleep(1)
    start_app('cn.youth.news')
    start_home()


def start_home():
    sleep(15)
    l9 = poco(type="android.widget.ImageView", name="cn.youth.news:id/l9")
    if l9.exists():
        l9.click()
    kn = poco(type="android.widget.ImageView", name="cn.youth.news:id/kn")
    if kn.exists():
        kn.click()
    sleep(1)
    select = random.randint(1, 2)
    if select == 1:
        # 视频
        a7p = poco(type="android.widget.TextView", name="cn.youth.news:id/a95")
        if a7p.exists():
            a7p.click()
        ul = poco(type="android.support.v7.widget.RecyclerView", name="cn.youth.news:id/ul")
        if ul.exists():
            ul.swipe([0, 0.5], duration=0.25)
        sleep(2)
        oh_list = poco(type="android.widget.LinearLayout", name="cn.youth.news:id/oh")
        sleep(1)
        if oh_list is not None and len(oh_list) > 0:
            for item in oh_list:
                item.click()
                break
            while True:
                loop_body()
    elif select == 2:
        # 新闻
        a3u = poco(type="android.widget.TextView", name="cn.youth.news:id/a5_")
        if a3u.exists():
            a3u.click()
        su = poco(type="android.support.v7.widget.RecyclerView", name="cn.youth.news:id/su")
        if su.exists():
            su.swipe([0, 0.5], duration=0.25)
        sleep(2)
        recursive()


def recursive():
    su_list = poco(type="android.support.v7.widget.RecyclerView", name="cn.youth.news:id/ul").children()
    if su_list.exists():
        for item in su_list:
            sleep(0.5)
            ad = item.offspring("cn.youth.news:id/a5o", textMatches=".*广告.*")
            play = item.offspring("cn.youth.news:id/l2")
            if not ad.exists() and not play.exists():
                item.click()

                count = random.randint(3, 5)
                for index in range(count):
                    loop_body2()
                l5 = poco(type="android.widget.ImageView", name="cn.youth.news:id/l5")
                if l5.exists():
                    l5.click()
                back = poco(type="android.widget.ImageView", name="cn.youth.news:id/l4")
                if back.exists():
                    back.click()
    # 上拉
    su = poco(type="android.support.v7.widget.RecyclerView", name="cn.youth.news:id/ul")
    if su.exists():
        su.swipe([0, -1], duration=0.25)
        sleep(2)
        recursive()


@timeout_decorator.timeout(120)
def loop_body():
    print('loop_body......')
    sleep(1)
    h7 = poco(type="android.widget.FrameLayout", name="cn.youth.news:id/h7")
    if h7.exists():
        ad = h7.offspring("cn.youth.news:id/a1f", textMatches=".*广告.*")
        if ad.exists():
            ad.click()
    # 奖励进度条
    rr = poco(type="android.widget.RelativeLayout", name="cn.youth.news:id/rr")
    try:
        rr.wait_for_appearance(30)
    except Exception as e:
        pass
    while True:
        rr2 = poco(type="android.widget.RelativeLayout", name="cn.youth.news:id/rr")
        if not rr2.exists():
            break
        sleep(1)
    fl = poco("cn.youth.news:id/zl").offspring("cn.youth.news:id/vo").child("android.widget.FrameLayout")
    if fl.exists():
        fl.swipe([0, -0.5], duration=1)
        sleep(0.5)
    vn_list = poco(type="android.widget.RelativeLayout", name="cn.youth.news:id/vn")
    if vn_list is not None and len(vn_list) > 0:
        for item in vn_list:
            a1f = item.offspring("cn.youth.news:id/a2v", textMatches=".*广告.*")
            if a1f.exists():
                continue
            else:
                item.click()
                break


@timeout_decorator.timeout(120)
def loop_body2():
    print('loop_body2......')
    if exists(Template(r"img/tpl_zhongqingkandian_back_btn.png", record_pos=(-0.42, -0.757), resolution=(1440, 2560))):
        touch(Template(r"img/tpl_zhongqingkandian_back_btn.png", record_pos=(-0.42, -0.757), resolution=(1440, 2560)))
    sleep(1)
    webview = poco("cn.youth.news:id/zl").offspring("android.webkit.WebView")
    if webview.exists():
        webview.swipe([0, -0.8], duration=1)
        sleep(0.5)
    more = webview.offspring(type="android.view.View", name="查看全文，奖励更多")
    if more.exists():
        more.click()


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
